<template>
  <div>
    <!--搜索表单-->
    <el-form :model="searchForm" ref="searchForm" label-width="100px" class="demo-searchForm">
      <el-popover
          placement="top"
          width="1250"
          v-model="visible">
        <div style="width: 1200px;display: flex;flex-wrap: wrap;height: 300px" title="高级搜索">
          <el-form-item label="广告标题" prop="adHeadline">
            <el-input v-model="searchForm.adHeadline" style="width: 200px"/>
          </el-form-item>
          <el-form-item label="创建时间" required>
            <el-date-picker
                v-model="createParams.dateTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="createDateTimeFormat"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="推送时间" required>
            <el-date-picker
                v-model="upParams.dateTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="upDateTimeFormat"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态" prop="isStatus">
            <el-select v-model="searchForm.isStatus">
              <el-option label="已生效" value="0"></el-option>
              <el-option label="已过期" value="1"></el-option>
              <el-option label="已上架" value="2"></el-option>
              <el-option label="已下架" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="失效日期" required>
            <el-date-picker
                v-model="useParams.dateTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="useDateTimeFormat"
            >
            </el-date-picker>
          </el-form-item>
        </div>
        <div style="text-align: right; margin: 0">
          <el-button type="primary" @click="selectList()">搜索</el-button>
          <el-button @click="clearSearchForm()">重置</el-button>
          <el-button type="text" @click="closeSearch()">取消</el-button>
        </div>
      </el-popover>
      <div style="display: flex; margin-left: 10px; width: 1300px; height: 40px; margin-bottom: 50px">
        <el-form-item>
          <el-input v-model="searchForm.adHeadline" placeholder="请输入标题" style="width: 300px"/>
        </el-form-item>
        <el-button style="margin-left: 50px" @click="selectList()">搜索</el-button>
        <el-button style="margin-left: 50px" @click="visible = true;">高级搜索</el-button>
        <el-button style="margin-left: 50px" @click="goToAdd()" type="primary">添加</el-button>
      </div>
    </el-form>
    <!--展示表格-->
    <el-table
        :data="tableData"
        style="width: 100%"
    >
      <el-table-column label="ID" prop="id" width="120">
        <template slot-scope="scope">
          <!-- 使用padStart方法来确保ID是9位的，如果不足则用0填充 -->
          <el-link :underline="false" @click="handleClick(scope.row.id)" style="color:blue">
            {{ scope.row.id.toString().padStart(9, '0') }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="广告标题" prop="adHeadline" width="120"/>
      <el-table-column label="时长/s" prop="time" width="200"/>
      <el-table-column label="推送时间" prop="upDateTime" :formatter="formatDateTime"/>
      <el-table-column label="失效日期" prop="downDateTime" :formatter="formatDateTime"/>
      <el-table-column label="创建时间" prop="createDateTime" :formatter="formatDateTime"/>
      <el-table-column label="状态" prop="isStatus" width="120">
        <template slot-scope="scope">
          {{
            scope.row.isStatus === 0 ? '生效中' : scope.row.isStatus === 1 ? '已过期' : scope.row.isStatus === 2 ? '已上架' : scope.row.isStatus === 3 ? '已下架' : '未知'
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template slot-scope="scope">
          <el-button
              @click="setId(scope.row.id)"
              type="text"
              size="small">
            <span style="color: #409EFF;font-size: larger; font-weight: bold;">&hellip;</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页展示-->
    <div class="block">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum"
          :page-sizes="[4, 8, 12, 16]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--操作-->
    <div v-if="showDiv" class="fixed-div">
      <el-button @click="updateUp=true" icon="el-icon-s-promotion"
                 style="color: deepskyblue;margin:0 auto;border-style: none;margin-top: 30px"><font
          color="black">重新推送</font></el-button>
      <el-button @click="status=3;updateStatus()" icon="el-icon-remove-outline"
                 style="color: red;margin:0 auto;border-style: none"><font color="black">下架</font></el-button>
      <el-button @click="status=2;updateStatus()" icon="el-icon-success"
                 style="color: green;margin:0 auto;border-style: none"><font color="black">上架</font></el-button>
      <el-button @click="deleteAd()" icon="el-icon-delete-solid" style="color: red;margin:0 auto;border-style: none">
        <font color="black">删除</font></el-button>
    </div>
    <!--重新推送操作-->
    <el-dialog title="提示" :visible.sync="updateUp" width="500px">
      <div align="left">
        <el-button icon="el-icon-info" type="text" style="color: black">您确定重新推送该广告吗? 请设置推送时间~
        </el-button>
        <div style="margin: 20px">
          <el-form :model="updateUpForm" ref="updateUpForm" :rules="updateUpFormRules">
            <el-form-item prop="upDateTime">
              <el-date-picker
                  v-model="updateUpForm.upDateTime"
                  type="datetime"
                  placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <span style="color: lightgray;font-size: small">推送时间必须大于当前时间</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="newUp()">确 定</el-button>
        <el-button @click="updateUp = false; resetForm('updateUpForm')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getList, updateStatus} from "@/api/ad/splitAdvertising"

export default {
  name: "SplitAdvertising",
  data() {
    return {
      updateUp: false,
      updateUpForm: {
        upDateTime: '',
      },
      formLabelWidth: '50px',
      showDiv: false, // 控制 div 显示状态
      location: [],
      status: 0,
      statusId: '',
      createParams: {
        dateTime: '',
      },
      upParams: {
        dateTime: '',
      },
      useParams: {
        dateTime: '',
      },
      total: 0,
      tableData: [],
      visible: false,
      searchForm: {
        splitOrStandby: 0,
        pageSize: 4,
        pageNum: 1,
        adHeadline: '',
        isStatus: '',
        useStartDate: '',
        useEndDate: '',
        upStartDate: '',
        upEndDate: '',
        createStartDate: '',
        createEndDate: '',
      },
      updateUpFormRules:{
        upDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('推送时间不能为空'));
              }
              const currentTime = new Date();
              currentTime.setHours(currentTime.getHours() + 1); // 可以设置为当前时间之后的时间，这里示例为当前时间1小时后
              if (value < currentTime) {
                callback(new Error('推送时间必须大于当前时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
    }
  },
  methods: {
    /*去添加页面*/
    goToAdd() {
      this.$router.push({path: "/addSplitAdvertising", query: {id: 0}});
    },
    /*重新推送*/
    newUp() {
      this.$refs.updateUpForm.validate((valid) => {
        if (valid) {
          const data = {
            id: this.statusId,
            upDateTime: this.updateUpForm.upDateTime,
            isStatus: 0
          }
          updateStatus(data).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.statusId = '';
              this.updateUp = false;
              this.resetForm('updateUpForm');
              this.selectList();
            } else {
              this.$message({
                message: '操作失败',
                type: 'warning'
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    /*重置搜索表单*/
    clearSearchForm() {
      this.resetForm('searchForm');
      this.createParams = {
        dateTime: '',
      }
      this.upParams = {
        dateTime: '',
      }
      this.useParams = {
        dateTime: '',
      }
      this.selectList();
    },
    /*修改状态*/
    updateStatus() {
      this.showDiv = !this.showDiv;
      const statusText = this.status === 3 ? '下架' : '上架';
      this.$confirm('是否确认'+statusText+'?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: this.statusId,
          isStatus: this.status
        }
        updateStatus(data).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.statusId = '';
            this.selectList();
          } else {
            this.$message({
              message: '操作失败',
              type: 'warning'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    deleteAd(){
      this.showDiv = !this.showDiv;
      this.$confirm('是否确认删除该广告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: this.statusId,
          isDel: 1
        }
        updateStatus(data).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.statusId = '';
            this.selectList();
          } else {
            this.$message({
              message: '操作失败',
              type: 'warning'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    /*点击给要修改的id赋值*/
    setId(id) {
      this.statusId = id;
      this.showDiv = !this.showDiv;
    },
    /*规范时间格式*/
    formatDateTime(row, column) {
      // 获取单元格数据
      let data = row[column.property]
      if (data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    },
    /*关闭高级搜索*/
    closeSearch() {
      this.visible = false;
      this.createParams = {
        dateTime: '',
      }
      this.upParams = {
        dateTime: '',
      }
      this.useParams = {
        dateTime: '',
      }
      this.resetForm('searchForm');
      this.selectList();
    },
    /*分割时间区间赋值*/
    useDateTimeFormat(picker) {
      if (Array.isArray(picker)) {
        this.searchForm.useStartDate = picker[0];
        this.searchForm.useEndDate = picker[1];
      }
    },
    upDateTimeFormat(picker) {
      if (Array.isArray(picker)) {
        this.searchForm.upStartDate = picker[0];
        this.searchForm.upEndDate = picker[1];
      }
    },
    createDateTimeFormat(picker) {
      if (Array.isArray(picker)) {
        this.searchForm.createStartDate = picker[0];
        this.searchForm.createEndDate = picker[1];
      }
    },
    /*搜索 表格展示*/
    selectList() {
      getList(this.searchForm).then(response => {
        this.tableData = response.data;
        this.total = response.total;
      });
    },
    /*动态分页*/
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.selectList();
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.selectList();
    },
    /*重置表单*/
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClick(id) {
      this.$router.push({path: "/splitAdDetail", query: {id: id}});
    }
  },
  created() {
    this.selectList();
  }
}
</script>

<style scoped>
.fixed-div {
  position: fixed;
  top: 300px; /* 距离窗口顶部20像素 */
  right: 10px; /* 距离窗口右侧20像素 */
  width: 125px;
  height: 200px;
  gap: 10px; /* 按钮之间的间距 */
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
</style>
